package com.ximu.image;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageCode extends HttpServlet {

	private static Random random = new  Random();
	
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * 此servelt生产用于生产一张验证码图片
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			String code = getCode();
			BufferedImage bi = getImage(code);
			response.setContentType("image/jpeg");
			ServletOutputStream out = response.getOutputStream();
			JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(out);
			encode.encode(bi);
			out.flush();
	}
	
	/**
	 * 在内存中创建一张图片
     * @param  code randomcode
	 * @return BufferedImage
	 */
	private BufferedImage getImage(String code){
		int width = Integer.parseInt(this.getInitParameter("width"));
		int height = Integer.parseInt(this.getInitParameter("height"));
		//分配一个图片缓冲区域
		BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		//获取绘制图像对象
		Graphics2D g = bi.createGraphics();
		//填充背景
		g.setColor(getColor());
		g.fillRect(0, 0, width, height);
		//设置字体
		g.setFont(new Font(Font.DIALOG,Font.BOLD,14));
		//设置字体颜色
		g.setColor(getColor());
		//将文字打印到图片
		g.drawString(code, 0, 20);
		return bi;
	}
	
	/**
	 * 获取一个随机颜色
	 * @return
	 */
	private static Color getColor(){
		return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
	}
	/**
	 * 获取验证码
	 * @return String
	 */
	private String getCode(){
		char[] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
						'o','p','q','r','s','t','u','v','w','x','y','z'};
		StringBuffer code = new StringBuffer();
		int length = Integer.parseInt(this.getInitParameter("length"));
		for(int i=0;i<length;i++){
			code.append(chars[random.nextInt(chars.length-1)]);
		}
		return code.toString();
	}

}
